#include <stm8s_tim2.h>

void TIM2_PWMIConfig(TIM2_Channel_TypeDef TIM2_Channel,
                     TIM2_ICPolarity_TypeDef TIM2_ICPolarity,
                     TIM2_ICSelection_TypeDef TIM2_ICSelection,
                     TIM2_ICPSC_TypeDef TIM2_ICPrescaler,
                     uint8_t TIM2_ICFilter)
{
  uint8_t icpolarity = (uint8_t)TIM2_ICPOLARITY_RISING;
  uint8_t icselection = (uint8_t)TIM2_ICSELECTION_DIRECTTI;
  
  /* Check the parameters */
  assert_param(IS_TIM2_PWMI_CHANNEL_OK(TIM2_Channel));
  assert_param(IS_TIM2_IC_POLARITY_OK(TIM2_ICPolarity));
  assert_param(IS_TIM2_IC_SELECTION_OK(TIM2_ICSelection));
  assert_param(IS_TIM2_IC_PRESCALER_OK(TIM2_ICPrescaler));
  
  /* Select the Opposite Input Polarity */
  if (TIM2_ICPolarity != TIM2_ICPOLARITY_FALLING)
  {
    icpolarity = (uint8_t)TIM2_ICPOLARITY_FALLING;
  }
  else
  {
    icpolarity = (uint8_t)TIM2_ICPOLARITY_RISING;
  }
  
  /* Select the Opposite Input */
  if (TIM2_ICSelection == TIM2_ICSELECTION_DIRECTTI)
  {
    icselection = (uint8_t)TIM2_ICSELECTION_INDIRECTTI;
  }
  else
  {
    icselection = (uint8_t)TIM2_ICSELECTION_DIRECTTI;
  }
  
  if (TIM2_Channel == TIM2_CHANNEL_1)
  {
    /* TI1 Configuration */
    TI1_Config((uint8_t)TIM2_ICPolarity, (uint8_t)TIM2_ICSelection,
               (uint8_t)TIM2_ICFilter);
    
    /* Set the Input Capture Prescaler value */
    TIM2_SetIC1Prescaler(TIM2_ICPrescaler);
    
    /* TI2 Configuration */
    TI2_Config(icpolarity, icselection, TIM2_ICFilter);
    
    /* Set the Input Capture Prescaler value */
    TIM2_SetIC2Prescaler(TIM2_ICPrescaler);
  }
  else
  {
    /* TI2 Configuration */
    TI2_Config((uint8_t)TIM2_ICPolarity, (uint8_t)TIM2_ICSelection,
               (uint8_t)TIM2_ICFilter);
    
    /* Set the Input Capture Prescaler value */
    TIM2_SetIC2Prescaler(TIM2_ICPrescaler);
    
    /* TI1 Configuration */
    TI1_Config((uint8_t)icpolarity, icselection, (uint8_t)TIM2_ICFilter);
    
    /* Set the Input Capture Prescaler value */
    TIM2_SetIC1Prescaler(TIM2_ICPrescaler);
  }
}

/**
  * @brief  Enables or disables the TIM2 peripheral.
  * @param   NewState new state of the TIM2 peripheral. This parameter can
  * be ENABLE or DISABLE.
  * @retval None
  */
